extends Node2D
class_name BurnEffect

@export var burn_particles: GPUParticles2D
@export var burn_sprite: AnimatedSprite2D

var is_burning = false
var burn_timer = 0.0
var burn_interval = 0.1  # 每0.1秒产生一个粒子

func _ready():
	# 初始化燃烧特效
	if burn_particles:
		burn_particles.emitting = false
	if burn_sprite:
		burn_sprite.visible = false

func start_burning():
	is_burning = true
	if burn_particles:
		burn_particles.emitting = true
	if burn_sprite:
		burn_sprite.visible = true
		burn_sprite.play("burn")

func stop_burning():
	is_burning = false
	if burn_particles:
		burn_particles.emitting = false
	if burn_sprite:
		burn_sprite.visible = false
		burn_sprite.stop()

func _process(delta):
	if is_burning:
		burn_timer += delta
		if burn_timer >= burn_interval:
			burn_timer = 0.0
			_create_burn_particle()

func _create_burn_particle():
	# 创建燃烧粒子效果
	var particle = Node2D.new()
	add_child(particle)
	
	# 创建火焰粒子精灵
	var sprite = Sprite2D.new()
	sprite.texture = _create_flame_texture()
	sprite.modulate = Color(randf_range(0.8, 1.0), randf_range(0.3, 0.7), 0.0, 1.0)
	particle.add_child(sprite)
	
	# 随机位置（在玩家周围）
	var random_offset = Vector2(randf_range(-20, 20), randf_range(-30, -10))
	particle.global_position = get_parent().global_position + random_offset
	
	# 随机大小
	var scale_factor = randf_range(0.5, 1.5)
	particle.scale = Vector2(scale_factor, scale_factor)
	
	# 创建上升动画
	var tween = create_tween()
	tween.tween_property(particle, "global_position", particle.global_position + Vector2(0, -50), 1.0)
	tween.parallel().tween_property(particle, "modulate:a", 0.0, 1.0)
	tween.parallel().tween_property(particle, "scale", Vector2(0.1, 0.1), 1.0)
	tween.tween_callback(particle.queue_free)

func _create_flame_texture() -> Texture2D:
	# 创建火焰纹理
	var image = Image.create(8, 8, false, Image.FORMAT_RGBA8)
	image.fill(Color(0, 0, 0, 0))  # 透明背景
	
	# 火焰颜色
	var colors = [
		Color(1, 0.8, 0, 1),    # 黄色
		Color(1, 0.5, 0, 1),    # 橙色
		Color(1, 0.3, 0, 1),    # 红色
		Color(1, 0.9, 0.3, 1)   # 亮黄色
	]
	
	# 创建火焰形状
	for x in range(8):
		for y in range(8):
			if randf() > 0.3:  # 70%概率设置像素
				var color = colors[randi() % colors.size()]
				image.set_pixel(x, y, color)
	
	var texture = ImageTexture.create_from_image(image)
	return texture 
